#include "myinet.h"
#include "tools.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

// 对应第九章，使用循环实现time server


int
main(int argc, char** argv){

    if (argc < 2){
        fprintf(stderr, "Usage: %s <port number>\n", argv[0]);
        exit(-1);
    }


    int portNumber = atoi(argv[1]);
    int sockfd = get_server_socket(portNumber, SOCK_DGRAM, 0);
    if (sockfd < 0) {
        error_exit("", 0);
    }

    struct sockaddr_in incomming_addr;
    socklen_t addrlen = sizeof(incomming_addr);
    time_t now;
    char buf[16];

    info("listening to %d", portNumber);
    while (recvfrom(sockfd, &buf
                , 0, 0, (struct sockaddr*)&incomming_addr, &addrlen) >= 0){
        time(&now);
        info("received from %s:%d", inet_ntoa(incomming_addr.sin_addr), 
                ntohs(incomming_addr.sin_port));

        // 发送时间
        int size = sendto(sockfd, (char*)&now
                , sizeof(time_t), 0, (struct sockaddr*)&incomming_addr, addrlen);
        if (size < 0)
            perror("sendto");
        info("%d bytes writen", size);
    }

    return 0;
}
